#ifndef USBTHREAD_H
#define USBTHREAD_H

#include <QObject>
#include <QThread>
#include <QDebug>
#include <QDateTime>
#include <QList>
#include <QHash>

extern quint32 program_version;

#include "hidapi/hidapi.h"

#define USB_MAX_DATA_LENGTH 64

typedef enum {USB_CONNECT=0,USB_DISCONNECT}_USB_STATUS;

struct HidDeviceInfo
{
    HidDeviceInfo(hid_device_info* info)
    {
        path = QString::fromLocal8Bit(info->path);
        vid = info->vendor_id;
        pid = info->vendor_id;
        serialNum = QString::fromWCharArray(info->serial_number);
        releaseNum = info->release_number;
        manufacturerStr = QString::fromWCharArray(info->manufacturer_string);
        productStr = QString::fromWCharArray(info->product_string);
        usage_page = info->usage_page;
        usage = info->usage;
        interfaceNum = info->interface_number;
    }
    friend QDebug& operator<<(QDebug out, const HidDeviceInfo& info)
    {

        out << info.path << "|" << info.serialNum<<info.releaseNum<<info.manufacturerStr<<info.productStr<<"|"<<info.interfaceNum;
        return out;
    }
    QString path;           // Platform-specific device path
    uint16_t vid;           // Device Vendor ID
    uint16_t pid;           // Device Product ID
    QString serialNum;      // Serial Number
    uint16_t releaseNum;    // Device Release Number in BCD
    QString manufacturerStr;// Manufacturer String
    QString productStr;     // Product string
    uint16_t usage_page;    // Usage Page for this Device/Interface (Windows/Mac only).
    uint16_t usage;         // Usage for this Device/Interface (Windows/Mac only).
    uint16_t interfaceNum;  // The USB interface which this logical device represents.
};

class USBThread : public QThread
{
    Q_OBJECT

private:
    bool thread_stop;       //true表示停止线程    false表示运行线程
    bool thread_pause = true;      //true表示暂停线程，即休眠    false表示运行线程
    bool thread_send;       //true表示有待发送的数据

    unsigned char usb_read_data[USB_MAX_DATA_LENGTH];

    char report_id;

    int usb_write_length;
    unsigned char *usb_write_buf;
    //bool usb_write;

    qint64 tick;

    hid_device *usbthread_handle;

    _USB_STATUS status;

protected:
    void    run() Q_DECL_OVERRIDE;  //线程任务


public:
    explicit USBThread(QObject *parent = nullptr);
    QList<HidDeviceInfo> get_device_list();
    //QList<HidDeviceInfo> hid_device_list;
    unsigned short vid;
    unsigned short pid;

    void pause_thread();
    void continue_thread();
    void stop_thread();

    bool open_usb(QString usb_path);

    void send_data(const QByteArray & data);       //向USB发送数据

    _USB_STATUS get_usbstatus();

signals:
    void new_data(const QByteArray);        //收到新数据

    void usb_connect(QString dev_str);
    void usb_disconnect();
    void usb_send_error();


};

#endif // USBTHREAD_H
